package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/honwee/awm/internal/api/router"
	"github.com/honwee/awm/pkg/logger"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Server 服务器结构体
type Server struct {
	engine *gin.Engine
	router *router.Router
	log    *zap.SugaredLogger
}

// NewServer 创建新的服务器实例
func NewServer(engine *gin.Engine, router *router.Router) *Server {
	return &Server{
		engine: engine,
		router: router,
		log:    logger.Logger.Sugar(),
	}
}

// Run 运行服务器
func (s *Server) Run() error {
	// 设置路由
	s.router.Setup()

	// 创建HTTP服务器
	srv := &http.Server{
		Addr:    ":8080",
		Handler: s.engine,
	}

	// 在goroutine中启动服务器
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			s.log.Fatalw("Failed to start server", "error", err)
		}
	}()

	s.log.Info("Server is running on :8080")

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	s.log.Info("Shutting down server...")

	// 设置关闭超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 优雅关闭服务器
	if err := srv.Shutdown(ctx); err != nil {
		s.log.Errorw("Server forced to shutdown", "error", err)
		return fmt.Errorf("server forced to shutdown: %w", err)
	}

	s.log.Info("Server exiting")
	return nil
}
